package com.wzdigit.wms.raw.service.asn.report;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wzdigit.framework.Shift;
import com.wzdigit.wms.basic.client.Pager;
import com.wzdigit.wms.basic.client.PagerInfo;
import com.wzdigit.wms.basic.client.response.Result;
import com.wzdigit.wms.basic.domain.asn.AsnDtl;
import com.wzdigit.wms.basic.domain.asn.AsnDtlGoods;
import com.wzdigit.wms.basic.domain.inventory.Goods;
import com.wzdigit.wms.basic.enums.*;
import com.wzdigit.wms.basic.mapper.core.inventory.GoodsMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnDtlGoodsMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnDtlMapper;
import com.wzdigit.wms.common.entity.ExcelExportConfig;
import com.wzdigit.wms.common.utils.HttpExcel;
import com.wzdigit.wms.basic.util.HttpSessionUtil;
import com.wzdigit.wms.common.utils.QueryInUtil;
import com.wzdigit.wms.raw.client.request.asn.report.asnreceive.AsnReceiveExportRequest;
import com.wzdigit.wms.raw.client.request.asn.report.asnreceive.AsnReceiveSearchRequest;
import com.wzdigit.wms.raw.client.request.trsn.report.asntrsn.AsnTrsnRequest;
import com.wzdigit.wms.raw.client.response.asn.receive.AsnReceieveEnums;
import com.wzdigit.wms.raw.client.response.asn.report.asnreceive.AsnReceiveDtlRespone;
import com.wzdigit.wms.raw.client.response.asn.report.asnreceive.AsnReceiveExportExt;
import com.wzdigit.wms.raw.client.response.asn.report.asnreceive.AsnReceiveGoodsRespone;
import com.wzdigit.wms.raw.client.response.asn.report.asnreceive.AsnReceiveHeaderRespone;
import com.wzdigit.wms.raw.client.response.asn.report.ortherasn.OrtherAsnEnums;
import com.wzdigit.wms.raw.client.response.trsn.report.asntrsn.AsnTrsnResponse;
import com.wzdigit.wms.raw.mapper.asn.report.AsnReceiveReportMapper;
import com.wzdigit.wms.raw.mapper.asn.report.OrtherAsnMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 送货单报表BS端Service
 * Created by zyf on 2021/7/16 14:16
 */
@Service
@Slf4j
public class AsnReceiveReportService {
    private List<String> asnTypeList= Arrays.asList("R14","R13");
    @Autowired
    private AsnDtlMapper asnDtlMapper;
    @Autowired
    private AsnDtlGoodsMapper asnDtlGoodsMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private AsnReceiveReportMapper receiveReportMapper;

    //分页查询主档信息
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<AsnReceiveHeaderRespone>> searchHeader(
            AsnReceiveSearchRequest search, Pager<?> pager){
        if(search!=null){
            if (search.getBeginTime()!=null){
                search.setBeginTimeDate(new Date(search.getBeginTime()));
            }
            if (search.getEndTime()!=null){
                search.setEndTimeDate(new Date(search.getEndTime()));
            }
            if (search.getBeginShipTime()!=null){
                search.setBeginShipTimeDate(new Date(search.getBeginShipTime()));
            }
            if (search.getEndShipTime()!=null){
                search.setEndShipTimeDate(new Date(search.getEndShipTime()));
            }
        }
        Page<AsnReceiveHeaderRespone> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        List<AsnReceiveHeaderRespone> datas = receiveReportMapper.selectHeader(search,asnTypeList);
        if (!CollectionUtil.isEmpty(datas)){
            for (AsnReceiveHeaderRespone data : datas) {
                if (data.getAsnType()!=null){
                    AsnTypeEnum asnTypeEnum = AsnTypeEnum.getEnumByCode(data.getAsnType());
                    if (asnTypeEnum!=null){
                        data.setAsnTypeStr(asnTypeEnum.enumName);
                    }
                }
                if (data.getHeaderStatus()!=null){
                    AsnHeaderStatusEnum statusEnum =
                            AsnHeaderStatusEnum.getEnumByCode(data.getHeaderStatus());
                    if (statusEnum!=null){
                        data.setHeaderStatusStr(statusEnum.enumName);
                    }
                }
            }
        }
        PagerInfo<List<AsnReceiveHeaderRespone>> pagerInfo = new PagerInfo<>();
        pagerInfo.setTotalCount(page.getTotal());
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //分页查询明细主页
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<AsnReceiveDtlRespone>> searchDtl(
            BigDecimal asnHeaderId, Pager<?> pager){
        Page<AsnReceiveDtlRespone> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        List<AsnReceiveDtlRespone> datas = receiveReportMapper.selectDtlList(asnHeaderId);
        if (!CollectionUtil.isEmpty(datas)){
            for (AsnReceiveDtlRespone data : datas) {
                if (data.getQcResult()!=null){
                    if (data.getQcResult().equals(QmsOqcStatusEnum.CHECK_ACCESS.getCode())){
                        data.setQcResultString(QmsOqcStatusEnum.JUDGE_RESULT_SUCCESS.getEnumByName());
                    }
                    if (data.getQcResult().equals(QmsOqcStatusEnum.CHECK_CONVICTED_BACK.getCode())){
                        data.setQcResultString(QmsOqcStatusEnum.JUDGE_RESULT_FAIL.getEnumByName());
                    }
                }

                if(data.getHoldCode()!=null){
                    data.setIsHold(true);
                }

                /*if (BigDecimal.ZERO.equals(data.getRcvQty())){
                    data.setAsnLine("待收货");
                }else if (data.getOrderQty().compareTo(data.getRcvQty())==1){
                    data.setAsnLine(AsnDtlStatusEnum.PARTRECEIVE.enumName);
                } else {
                    data.setAsnLine(AsnDtlStatusEnum.WHOLERECEIVE.enumName);
                }*/
                if(data.getStatus()!=null){
                    AsnDtlStatusEnum statusEnum = AsnDtlStatusEnum.getEnumByCode(data.getStatus());
                    if(statusEnum!=null){
                        data.setAsnLine(statusEnum.enumName);
                    }
                }

                if (data.getQcStatus()!=null){
                    if (data.getQcStatus().equals(QcStatusEnum.未创建质检单.getCode())){
                        data.setQcStatusString(QcStatusEnum.未创建质检单.getEnumByName());
                    }else if (data.getQcStatus().equals(QcStatusEnum.已创建质检单.getCode())){
                        data.setQcStatusString(QcStatusEnum.已创建质检单.getEnumByName());
                    }else if (data.getQcStatus().equals(QcStatusEnum.部分质检.getCode())){
                        data.setQcStatusString(QcStatusEnum.部分质检.getEnumByName());
                    }else if (data.getQcStatus().equals(QcStatusEnum.全部质检.getCode())){
                        data.setQcStatusString(QcStatusEnum.全部质检.getEnumByName());
                    }else if (data.getQcStatus().equals(QcStatusEnum.质检取消.getCode())){
                        data.setQcStatusString(QcStatusEnum.质检取消.getEnumByName());
                    }else if (data.getQcStatus().equals(QcStatusEnum.质检关闭.getCode())){
                        data.setQcStatusString(QcStatusEnum.质检关闭.getEnumByName());
                    }
                }
            }
        }
        PagerInfo<List<AsnReceiveDtlRespone>> pagerInfo = new PagerInfo<>();
        pagerInfo.setTotalCount(page.getTotal());
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //分页查询序列
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<AsnReceiveGoodsRespone>> searchGoods(
            BigDecimal asnHeaderId, Pager<?> pager){
        Page<AsnReceiveGoodsRespone> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        List<AsnReceiveGoodsRespone> datas = receiveReportMapper.selectGoodsList(asnHeaderId);
        if (!CollectionUtil.isEmpty(datas)){
            for (AsnReceiveGoodsRespone data : datas) {
                data.setFlag(true);
            }
        }
        PagerInfo<List<AsnReceiveGoodsRespone>> pagerInfo = new PagerInfo<>();
        pagerInfo.setTotalCount(page.getTotal());
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //取消送货单
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<?> removeAsn(
            List<BigDecimal> asnHeaderIds,HttpServletRequest servletRequest, HttpServletResponse servletResponse){
        if (CollectionUtil.isEmpty(asnHeaderIds)){
            Shift.fatal("请选择发货单取消!");
        }
        //只能取消状态为新建的发货单
        List<Integer> status = receiveReportMapper.selectHeaderStatus(asnHeaderIds);
        for (Integer statu : status) {
            if (!statu.equals(AsnHeaderStatusEnum.CREATE.code)){
                Shift.fatal("只能取消状态新建的发货单!");
            }
        }
        //查询要删除的SN
        List<String> snList = receiveReportMapper.selectAsnSnList(asnHeaderIds);

        if (!CollectionUtil.isEmpty(snList)){
            List<List<String>> splitSnList = QueryInUtil.splitInParams(999, snList);
            for (List<String> splitSn : splitSnList) {
                asnDtlGoodsMapper.delete(new QueryWrapper<AsnDtlGoods>().in("GOODS_SN",splitSn));
                goodsMapper.delete(new QueryWrapper<Goods>().in("GOODS_SN",splitSn));
            }
        }
        asnDtlMapper.delete(new QueryWrapper<AsnDtl>().in("ASN_HEADER_ID",asnHeaderIds));
        receiveReportMapper.updateHeaderStatus(asnHeaderIds, HttpSessionUtil.getLoginName(servletRequest),new Date());
        return new Result<String>(true,"取消发货单成功!");
    }

    @Transactional
    public void exportAsnTrsnReport(
            AsnReceiveExportRequest search,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        ServletOutputStream out = null;
        XSSFWorkbook workbook = null;
        try {
            //设置查询
            search = this.setExportSearch(search);
            List<AsnReceiveExportExt> resultDatas = receiveReportMapper.exportExt(search,asnTypeList);

            if (!CollectionUtil.isEmpty(resultDatas)){
                for (AsnReceiveExportExt data : resultDatas) {
                    if (data.getAsnType()!=null){
                        AsnTypeEnum asnTypeEnum = AsnTypeEnum.getEnumByCode(data.getAsnType());
                        if (asnTypeEnum!=null){
                            data.setAsnTypeStr(asnTypeEnum.enumName);
                        }
                    }
                    if (data.getHeaderStatus()!=null){
                        AsnHeaderStatusEnum statusEnum =
                                AsnHeaderStatusEnum.getEnumByCode(data.getHeaderStatus());
                        if (statusEnum!=null){
                            data.setHeaderStatusStr(statusEnum.enumName);
                        }
                    }
                    if (data.getQcResult()!=null){
                        if (data.getQcResult().equals(QmsOqcStatusEnum.CHECK_ACCESS.getCode())){
                            data.setQcResultString(QmsOqcStatusEnum.JUDGE_RESULT_SUCCESS.getEnumByName());
                        }
                        if (data.getQcResult().equals(QmsOqcStatusEnum.CHECK_CONVICTED_BACK.getCode())){
                            data.setQcResultString(QmsOqcStatusEnum.JUDGE_RESULT_FAIL.getEnumByName());
                        }
                    }

                    if(data.getHoldCode()!=null){
                        data.setIsHold(true);
                    }
                    if (data.getHoldCode()!=null){
                        if (data.getHoldCode().equals(true)){
                            data.setIsHoldStr("是");
                        }else {
                            data.setIsHoldStr("否");
                        }
                    }

                    /*if (BigDecimal.ZERO.equals(data.getRcvQty())){
                        data.setAsnLine("待收货");
                    }else if (data.getOrderQty().compareTo(data.getRcvQty())==1){
                        data.setAsnLine(AsnDtlStatusEnum.PARTRECEIVE.enumName);
                    } else {
                        data.setAsnLine(AsnDtlStatusEnum.WHOLERECEIVE.enumName);
                    }*/
                    if(data.getStatus()!=null){
                        AsnDtlStatusEnum statusEnum = AsnDtlStatusEnum.getEnumByCode(data.getStatus());
                        if(statusEnum!=null){
                            data.setDtlStatus(statusEnum.enumName);
                        }
                    }

                    if (data.getQcStatus()!=null){
                        if (data.getQcStatus().equals(QcStatusEnum.未创建质检单.getCode())){
                            data.setQcStatusString(QcStatusEnum.未创建质检单.getEnumByName());
                        }else if (data.getQcStatus().equals(QcStatusEnum.已创建质检单.getCode())){
                            data.setQcStatusString(QcStatusEnum.已创建质检单.getEnumByName());
                        }else if (data.getQcStatus().equals(QcStatusEnum.部分质检.getCode())){
                            data.setQcStatusString(QcStatusEnum.部分质检.getEnumByName());
                        }else if (data.getQcStatus().equals(QcStatusEnum.全部质检.getCode())){
                            data.setQcStatusString(QcStatusEnum.全部质检.getEnumByName());
                        }else if (data.getQcStatus().equals(QcStatusEnum.质检取消.getCode())){
                            data.setQcStatusString(QcStatusEnum.质检取消.getEnumByName());
                        }else if (data.getQcStatus().equals(QcStatusEnum.质检关闭.getCode())){
                            data.setQcStatusString(QcStatusEnum.质检关闭.getEnumByName());
                        }
                    }
                }
            }
            List<ExcelExportConfig> configs = new ArrayList<>();
            configs.add(new ExcelExportConfig("送货单号", "asnNo", 120));
            configs.add(new ExcelExportConfig("订单状态", "headerStatusStr", 120));
            configs.add(new ExcelExportConfig("单据来源", "dataSource", 120));
            configs.add(new ExcelExportConfig("单据类型", "asnTypeStr", 120));
            configs.add(new ExcelExportConfig("组织代码", "factory", 120));
            configs.add(new ExcelExportConfig("制单时间", "createTime", 120));
            configs.add(new ExcelExportConfig("审核时间", "approvedTime", 120));
            configs.add(new ExcelExportConfig("发货时间", "deliveryTime", 120));
            configs.add(new ExcelExportConfig("供应商编码", "vedorCode", 120));
            configs.add(new ExcelExportConfig("供应商描述", "vedorName", 120));
            configs.add(new ExcelExportConfig("供应商描述", "vedorName", 120));
            configs.add(new ExcelExportConfig("收货仓库", "whsName", 120));
            configs.add(new ExcelExportConfig("制单人", "createUser", 120));
            configs.add(new ExcelExportConfig("审核人", "approvedUser", 120));
            configs.add(new ExcelExportConfig("发货人", "deliveryUser", 120));
            configs.add(new ExcelExportConfig("联系人", "carrierName", 120));
            configs.add(new ExcelExportConfig("联系电话", "carrierPhone", 120));
            configs.add(new ExcelExportConfig("备注", "comments", 120));
            configs.add(new ExcelExportConfig("行号", "asnLine", 120));
            configs.add(new ExcelExportConfig("行状态", "dtlStatus", 120));
            configs.add(new ExcelExportConfig("成本中心", "costCenter", 120));
            configs.add(new ExcelExportConfig("物料编码", "skuCode", 120));
            configs.add(new ExcelExportConfig("物料描述", "skuDesc", 120));
            configs.add(new ExcelExportConfig("物料规格", "skuSpec", 120));
            configs.add(new ExcelExportConfig("采购订单号", "poNo", 120));
            configs.add(new ExcelExportConfig("采购订单行号", "poLineNo", 120));
            configs.add(new ExcelExportConfig("采购数量", "orderQty", 120));
            configs.add(new ExcelExportConfig("发货数量", "shipQty", 120));
            configs.add(new ExcelExportConfig("收货数量", "rcvQty", 120));
            configs.add(new ExcelExportConfig("采购单位", "poUnit", 120));
            configs.add(new ExcelExportConfig("是否冻结", "isHoldStr", 120));
            configs.add(new ExcelExportConfig("冻结原因", "holdReson", 120));
            configs.add(new ExcelExportConfig("质检状态", "qcStatusString", 120));
            configs.add(new ExcelExportConfig("检验结果", "qcResultString", 120));
            configs.add(new ExcelExportConfig("库存状态", "invAttr", 120));
            configs.add(new ExcelExportConfig("上架库位", "locName", 120));
            configs.add(new ExcelExportConfig("批次号", "lotno", 120));
            configs.add(new ExcelExportConfig("创建人员", "dtlCreateUser", 120));
            configs.add(new ExcelExportConfig("创建时间", "dtlCreateTime", 120));
            workbook = HttpExcel.newListToExcel(resultDatas, configs);
            String userAgent = servletRequest.getHeader("USER-AGENT");
            String fileName = "入库凭证报表";
            if (userAgent.contains("Mozilla")) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "utf8");
            }
            servletResponse.setContentType("application/octet-stream");
            servletResponse.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ".xlsx");
            servletResponse.flushBuffer();
            out = servletResponse.getOutputStream();
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
            if(workbook != null) {
                workbook.close();
            }
        }

    }

    //查询单据类型下拉框
    public List<OrtherAsnEnums> getAsnReceiveEnumsList(){
        List<OrtherAsnEnums> datas=new ArrayList<>();
        for (String asnTypeString : asnTypeList) {
            AsnTypeEnum asnTypeEnum = AsnTypeEnum.getEnumByCode(asnTypeString);
            if (asnTypeEnum!=null){
                OrtherAsnEnums data=new OrtherAsnEnums();
                data.setCode(asnTypeString);
                data.setEnumName(asnTypeEnum.getEnumName());
                datas.add(data);
            }
        }
        return datas;
    }

    //订单状态下拉框
    public List<AsnReceieveEnums> getAsnReceiveStatusEnum(){
        List<AsnReceieveEnums> results=new ArrayList<>();
        for (AsnHeaderStatusEnum value : AsnHeaderStatusEnum.values()){
            AsnReceieveEnums enums=new AsnReceieveEnums();
            enums.setCode(value.code);
            enums.setName(value.enumName);
            results.add(enums);
        }
        return results;
    }

    //设置查询条件
    private AsnReceiveExportRequest setExportSearch(AsnReceiveExportRequest search){
        if (search==null){
            return search;
        }
        if (CollectionUtil.isEmpty(search.getAsnHeaderIds())){
            if (search.getBeginTime()!=null){
                search.setBeginTimeDate(new Date(search.getBeginTime()));
            }
            if (search.getEndTime()!=null){
                search.setEndTimeDate(new Date(search.getEndTime()));
            }
            if (search.getBeginShipTime()!=null){
                search.setBeginShipTimeDate(new Date(search.getBeginShipTime()));
            }
            if (search.getEndShipTime()!=null){
                search.setEndShipTimeDate(new Date(search.getEndShipTime()));
            }
            return search;
        }
        AsnReceiveExportRequest result=new AsnReceiveExportRequest();
        result.setAsnHeaderIds(search.getAsnHeaderIds());
        return result;
    }



}
